﻿using BLL;
using DevExpress.XtraGrid.Views.Grid;
using Model;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.BLL;
using 后整理管理系统.其他窗体;
using 后整理管理系统.新增窗体;
using 后整理管理系统.自定义类;
using 纺织贸易管理系统;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.新增窗体;
using 纺织贸易管理系统.设置窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 流程卡查询 : Form
    {
        private List<Liuzhuancard> liuzhuancards = new List<Liuzhuancard> ();
        public 流程卡查询()
        {
            InitializeComponent();
            CreateGrid.Create(this.Name, uiDataGridView1 );
            CreateGrid.Create("原料入库单", gridView2, "gridView1");
            uiDataGridView1.OptionsBehavior.Editable = false;
            try
            {
                uiDataGridView1.Columns["Card_Date"].DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";//设置时间显示格式
            }
            catch { }
            gridView2.OptionsBehavior.Editable = false;
            uiDatePicker2.Value = DateTime.Now.Date.AddDays(1).AddSeconds(-1);
            uiDatePicker1.Value = uiDatePicker2.Value.AddDays(-QueryTime.间隔);
        }

        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MainForm.mainform.AddMidForm(new 流转卡() { Useful=FormUseful.新增 }) ;
        }

        private void 流程卡查询_Load(object sender, EventArgs e)
        {
            query();
        }
        private void query()
        {
            try
            {
                this.ShowWaitForm("正在查询，请等待.............");
                //liuzhuancards =LiuzhuancardService.GetLiuzhuancardlst (x=>x.Card_Date >=uiDatePicker1.Value.Date &&x.Card_Date <=uiDatePicker2.Value.Date &&
                //x.Customer.Contains (txtkehu.Text )&&x.Color .Contains (txtyanse.Text )&&x.Pingming.Contains (txtpingming.Text ));
                liuzhuancards = LiuzhuancardService.GetLiuzhuancardlst($"Select distinct liuzhuancard.*  from liuzhuancard left join danjumingxitable on danjumingxitable.danhao=liuzhuancard.CardNum  where liuzhuancard.card_date between '{uiDatePicker1.Value.Date}' " +
                    $" and '{uiDatePicker2.Value.Date.AddDays(1)}' and liuzhuancard.CardNum like '%{txtliuzhuanka.Text}%' and liuzhuancard.Customer like '%{txtkehu.Text}%' and danjumingxitable.yanse like '%{txtyanse.Text.Replace("'", "''")}%' and danjumingxitable.pingming like '%{txtpingming.Text.Replace("'", "''")}%'" +
                    $" and danjumingxitable.ganghao like '%{txtganghao.Text.Replace("'", "''")}%' and danjumingxitable.orderNum like '%{txtOrderNum.Text.Replace("'", "''")}%'  order by liuzhuancard.id desc");
                //var res = new List<Liuzhuancard>();
                //foreach (string c in liuzhuancards.Select(x => x.CardNum).Distinct().ToList())
                //{
                //    res.Add(liuzhuancards.First(x => x.CardNum == c));
                //}
                gridControl2 .DataSource = liuzhuancards;
                this.HideWaitForm();
            }
            catch (Exception ex)
            {
                this.HideWaitForm();
                Tools.ShowMessageBox.ShowErrorBox("查询的时候发生了错误"+ex.Message);
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            query();
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode ==Keys.Enter )
            {
                query();
            }
        }

       
        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var liuzhuankahao = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
            if (liuzhuanlogService.Getliuzhuanloglst(x => x.CardNum == liuzhuankahao).Count > 0)
            {
                Sunny.UI.UIMessageBox.ShowError("该流转卡号" + liuzhuankahao + "已经存在操作日志！删除失败");
                return;
            }
            var mingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.offerid == liuzhuankahao && x.rkdh == x.danhao);
            foreach (var m in mingxis)
            {
                if (JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerPingMing == liuzhuankahao && x.SampleName == m.pingming && x.yanse == m.yanse && x.GangHao == m.ganghao).Count > 0)
                {
                    Sunny.UI.UIMessageBox.ShowError("该单据已经有对应的打卷信息！\r\n不能删除!\r\n请先删除对应的打卷信息");
                    return;
                }
            }
            if (mingxis.Where(x => x.InventoryQuantity == 0).Any())
            {
                Sunny.UI.UIMessageBox.ShowError("该卡的部分面料已经全部发完货了！\r\n不能删除!\r\n请先删除对应的发货信息");
                return;
            }
            string cardnum = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
            MainForm.mainform.AddMidForm(new 流转卡() { Useful = FormUseful.修改, liuzhuancard =LiuzhuancardService.GetOneLiuzhuancard  (x=>x.CardNum ==cardnum) });
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var liuzhuankahao = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
            if (liuzhuanlogService .Getliuzhuanloglst  (x=>x.CardNum==liuzhuankahao ).Count >0)
            {
                Sunny.UI.UIMessageBox.ShowError("该流转卡号" + liuzhuankahao + "已经存在操作日志！删除失败");
                return;
            }
            var mingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.offerid == liuzhuankahao&&x.rkdh==x.danhao);
            foreach (var m in mingxis)
            {
                if (JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerPingMing == liuzhuankahao && x.SampleName == m.pingming && x.yanse == m.yanse && x.GangHao == m.ganghao).Count > 0)
                {
                    Sunny.UI.UIMessageBox.ShowError("该单据已经有对应的打卷信息！\r\n不能删除!\r\n请先删除对应的打卷信息");
                    return;
                }
            }
            if(mingxis.Where (x=>x.InventoryQuantity==0).Count ()>0)
            {
                Sunny.UI.UIMessageBox.ShowError("该卡的部分面料已经全部发完货了！\r\n不能删除!\r\n请先删除对应的发货信息");
                return;
            }
            if (Sunny.UI.UIMessageBox.ShowAsk ($"您确定要删除{liuzhuankahao }该流转单吗?")==true )
            {
                try
                {
                    using (var trans = Connect.dbcontext.UseTran())
                    {
                        var CardNum = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
                        流转单BLL.删除流转卡(CardNum);
                        trans.CommitTran ();
                    }
                    AlterDlg.Show("删除成功");
                    query();
                }
                catch(Exception ex)
                {
                    Sunny.UI.UIMessageBox.ShowError ("删除失败！原因是：" + ex.Message);
                }              
            }
        }

     
        private void 流转登记ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (uiDataGridView1.FocusedRowHandle >=0 )
            {
                var fm = new 流转登记() { Useful = FormUseful.新增, Liuzhuankahao = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString()
            };
                fm.ShowDialog();
                uiDataGridView1_Click(uiDataGridView1 ,null);
            }
            else
            {
                var fm = new 流转登记() { Useful = FormUseful.新增 };
                fm.ShowDialog();
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog( "您确定要删除该流转工序吗？"))
            {
                if (uiDataGridView3.CurrentRow != null)
                {
                    int id = (int)uiDataGridView3.Rows[uiDataGridView3.CurrentRow.Index].Cells[ID.Name].Value;
                    var log = liuzhuanlogService.GetOneliuzhuanlog(x => x.ID == id);
                    string danhao = log.CardNum + log._date.ToString();
                    danjumingxitableService.Deletedanjumingxitable(x => x.danhao == danhao);
                    liuzhuanlogService.Deleteliuzhuanlog(x => x.ID == id);
                    UINotifier.Show("删除成功", UINotifierType.OK, "后整理管理系统", false, 2000, null);
                    uiDataGridView1_Click(null, null);
                }
                else
                {
                    AlterDlg.Show("没有任何记录被选中！");
                }
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (uiDataGridView3.CurrentRow != null)
            {
                var fm = new 流转登记() { Useful = FormUseful.修改, ID = (int)uiDataGridView3.Rows[uiDataGridView3.CurrentRow.Index].Cells[ID.Name].Value };
                fm.ShowDialog();
                uiDataGridView1_Click(null, null);
            }
            else
            {
                AlterDlg.Show("没有任何记录被选中！");
            }
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            try
            {
                var fm = new 配置列(uiDataGridView1) { formname = this.Name, Obj=new Liuzhuancard () };
                fm.ShowDialog();
            }
            catch
            {

            }
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name , this.uiDataGridView1 );
        }

        private void 分卡ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string cardnum = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
            new 流转卡拆分() { Useful = FormUseful.修改, liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == cardnum) }.ShowDialog ();
        }

        private void uiDataGridView1_Click(object sender, EventArgs e)
        {
            try
            {
                if (uiDataGridView1.FocusedRowHandle >= 0)
                {
                    string cardnum = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
                    uiDataGridView3.DataSource = liuzhuanlogService.Getliuzhuanloglst(x => x.CardNum == cardnum);
                    uiDataGridView4.DataSource = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == cardnum);
                    var liuzhuangkamingxi = liuzhuanmingxiService.Getliuzhuanmingxilst(x => x.CardNum == cardnum);
                    gridControl3.DataSource = Connect.dbcontext.Queryable<ImportAndExportOfRawMaterials>().Where(x => x.DocNum == cardnum).ToList ();
                    gridControl1.DataSource = liuzhuangkamingxi;
                    gridControl1.RefreshDataSource();
                   var card=uiDataGridView1.GetFocusedRow() as Liuzhuancard;
                    if (card != null) 
                    {
                        //ArrangementDoc
                        要求赋值(card.ArrangementDoc);
                    }
                }
            }
            catch (Exception ex)
            {
                Tools.ShowMessageBox.ShowErrorBox("查询的时候发生了错误：" + ex.Message);
            }
        }
        private void 要求赋值(string ArrangementDoc)
        {
            var requirements = Connect.dbcontext.Queryable<ProofingRequirements>().First(x => x.DocNum == ArrangementDoc);
            if (requirements == null)
            {
                requirements = new ProofingRequirements();
            }
            txtzhengfangmian.Text = requirements.FrontOrBack;
            txtshuiya.Text = requirements.Hydraulic;
            txtceshibiaozhun.Text = requirements.TestStandards;
            txtqiebian.Text = requirements.Trimming;
            txtshuixi.Text = requirements.Washing;
            txtfangshuixiaoguo.Text = requirements.WaterproofEffect;
            txtkezhong.Text = requirements.Weight;
            txtmenfu.Text = requirements.Width;
            txtgunxing.Text = requirements.Sticktype;
            txtjiaoshui.Text = requirements.Glue;
            txtdibu.Text = requirements.TPU;
            txtwendu.Text = requirements.Temperature;
            txttieheyali.Text = requirements.FitPressure;
            txtshoujuanyali.Text = requirements.RewindingPressure;
            txtshoujuanzhangli.Text = requirements.RewindingTension;
            TxtTopWeight.Text = requirements.TopWeight;
            txtBottomWeight.Text = requirements.BottomWeight;
            txtSeamSlippage.Text = requirements.SeamSlippage;
            txtDetectionmetrics.Text = requirements.DetectionMetrics;
            txtTearStrength.Text = requirements.TestStandards;
            txtOther.Text = requirements.Other;
            txtdivest.Text = requirements.Divest;
            txtgunxing1.Text = requirements.Sticktype1;
            txtjiaoshui1.Text = requirements.Glue1;
            txtguhuaji.Text = requirements.CuringAgent;
            txtrongji.Text = requirements.Solvent;
            txtguhuaji1.Text = requirements.CuringAgent1;
            txtrongji1.Text = requirements.Solvent1;
         }
        private void 安排生产ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (AccessBLL.CheckAccess("安排生产"))
            {
                if (ShowMessageBox.ShowAskBox("确定要把选中的流转卡安排生产吗？") == DialogResult.Yes)
                {
                    var selectLiuzhuanka = SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1);
                    if (selectLiuzhuanka.Count > 0)
                    {
                        ///检查是否已经有已经排产的  防止二次预出库
                        foreach (var row in selectLiuzhuanka)
                        {
                            if (row.IsArrangementProduced)
                            {
                                ShowMessageBox.ShowErrorBox($"该卡号{row.CardNum}已经安排生产了！不能二次排产\r\n请先取消掉该卡号的排产状态");
                                return;
                            }

                        }
                        try
                        {
                            var ProcessCard = SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1);
                            var mingxi = new List<liuzhuanmingxi>();
                            if (ProcessCard.Count > 0)
                            {
                                var fm = new 工艺二次登记(ProcessCard, FormUseful.新增, new ScheduleDoc());
                                fm.ShowDialog();
                            }
                            //if(mingxi.Count==0)
                            //{
                            //    this.ShowErrorDialog("没有任何工艺信息！排产失败");
                            //    return;
                            //}
                            //Connect.dbcontext.BeginTran();
                            //foreach (var cardnum in selectLiuzhuanka.Select(x=>x.CardNum ).Distinct ())
                            //{
                            //    流转单BLL.安排生产(cardnum, BianhaoBLL.CreatDanhao(FirstLetter.排产单, DateTime.Now, DanjuLeiXing.排产单),mingxi);
                            //}
                            //Connect.dbcontext.CommitTran();
                        }
                        catch (Exception ex)
                        {
                            Connect.dbcontext.RollbackTran();
                            ShowMessageBox.ShowErrorBox("排产失败，原因是:" + ex.Message);
                        }
                    }
                }
                query();
            }
        }

        private void 取消生产ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (ShowMessageBox.ShowAskBox("确定要把选中的流转卡安排生产吗？") == DialogResult.Yes)
            {
                var selectLiuzhuanka = SelectHelper.GetSelectList<Liuzhuancard>(uiDataGridView1);
                if (selectLiuzhuanka.Count > 0)
                {
                    ///检查是否已经有已经排产的  防止二次预出库
                    foreach (var row in selectLiuzhuanka)
                    {
                        if (!row.IsArrangementProduced)
                        {
                            ShowMessageBox.ShowErrorBox($"该卡号{row.CardNum}状态为未排产！无需取消\r\n取消操作失败");
                            return;
                        }
                    }                 
                    try
                    {
                       
                        Connect.dbcontext.BeginTran();
                        foreach (var cardnum in selectLiuzhuanka.Select(x => x.CardNum).Distinct())
                        {
                            流转单BLL.取消排产(cardnum);
                        }
                        Connect.dbcontext.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        Connect.dbcontext.RollbackTran();
                        ShowMessageBox.ShowErrorBox("取消排产失败，原因是:" + ex.Message);
                    }
                }
            }
            query();
        }

        private void gridControl2_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string cardnum = uiDataGridView1.GetRowCellValue(uiDataGridView1.FocusedRowHandle, "CardNum").ToString();
                MainForm.mainform.AddMidForm(new 流转卡() { Useful = FormUseful.查看, liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.CardNum == cardnum) });
            }
            catch (Exception ex) 
            {
                ShowMessageBox.ShowErrorBox("查看的时候发生了错误:"+ex.Message);
            }
        }

        private void uiDataGridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            try
            {
                // 假设我们基于某个条件来设置颜色
                if (e.RowHandle >= 0 && e.RowHandle < uiDataGridView1.RowCount)
                {
                    // 获取当前行的数据
                    var row = uiDataGridView1.GetRow(e.RowHandle) as Liuzhuancard;
                    // 假设我们根据某个字段的值来设置颜色
                    //string someFieldValue = row["InventoryQuantity"].ToString();

                    // 设置背景色和字体色
                    if (row.UrgencyLevel == "特急")
                    {
                        e.Appearance.ForeColor = Color.Red; // 设置背景色
                    }
                    // 设置背景色和字体色
                    if (row.UrgencyLevel == "比较急")
                    {
                        e.Appearance.ForeColor = Color.DodgerBlue; // 设置背景色
                    }
                }
            }
            catch(Exception ex)
            {
                ShowMessageBox.ShowErrorBox(ex.Message);
            }
        }

        private void uiDataGridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;
            if (view == null || e.RowHandle < 0) return;

            // 仅处理Rangchang列
            if (e.Column.FieldName == "State")
            {
                object cellValue = view.GetRowCellValue(e.RowHandle, "State");

                // 条件判断示例
                if (cellValue != null)
                {
                    string value = cellValue.ToString();
                    if (value == "退卷")
                    {
                        e.Appearance.BackColor = Color.Orange;
                        e.Appearance.ForeColor = Color.Black;
                    }
                    else if (value == "下机")
                    {
                        e.Appearance.BackColor = Color.Red;
                        e.Appearance.ForeColor = Color.White;
                    }
                    else if (value == "上机")
                    {
                        e.Appearance.BackColor = Color.Green;
                        e.Appearance.ForeColor = Color.White;
                    }
                }
            }
        }
    }
}
